package com.itheima.nio.tomcat.domain;

import org.apache.commons.io.IOUtils;

import java.io.*;
import java.net.PortUnreachableException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

public class HttpResponse {

    private String version;
    private String status;
    private String desc;
    private List<Header> headers = new ArrayList<>();
    private String contentType;
    private SelectionKey selectionKey;
    private HttpRequest httpRequest;
    public static final String WEB_APP_PATH = "itheima-nio-tomcat-4\\webapp";
    public HttpResponse(SelectionKey selectionKey) {
        this.selectionKey = selectionKey;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public List<Header> getHeaders() {
        return headers;
    }

    public void setHeaders(List<Header> headers) {
        this.headers = headers;
    }

    public String getContentType() {
        return contentType;
    }

    public void setContentType(String contentType) {
        Header header = new Header();
        header.setName("Content-Type");
        header.setValue(contentType);
        headers.add(header);
        this.contentType = contentType;
    }

    public SelectionKey getSelectionKey() {
        return selectionKey;
    }

    public void setSelectionKey(SelectionKey selectionKey) {
        this.selectionKey = selectionKey;
    }

    public HttpRequest getHttpRequest() {
        return httpRequest;
    }

    public void setHttpRequest(HttpRequest httpRequest) {
        this.httpRequest = httpRequest;
    }
    public void sendStaticResource(){
        this.version = "HTTP/1.1";
        String requestURI = httpRequest.getRequestURI();
        File file = new File(WEB_APP_PATH + requestURI);
        if (file.exists()){
            this.status = "200";
            this.desc = "OK";
        } else {
            this.status = "404";
            this.desc = "NOT FOUND";
        }
        String responseLine = this.version + " " + this.status + " " + this.desc + "\r\n";
        if (requestURI.endsWith("txt")){
            this.setContentType("text/html;charset=UTF-8");
        } else if (requestURI.endsWith("jpg")){
            this.setContentType("image/jpeg");
        } else if (requestURI.endsWith("ico")){
            this.setContentType("image/x-icon");
        }
        List<Header> headers = this.getHeaders();
        StringBuilder stringBuilder = new StringBuilder();
        for (Header header : headers){
            stringBuilder.append(header.getName() + ": " + header.getValue() + "\r\n");
        }
        String responseHeader = stringBuilder.toString();
        String responseEmptyLine = "\r\n";
        String responseLineAndHeaderAndEmptyLine = responseLine + responseHeader + responseEmptyLine;
        try {
            ByteBuffer byteBuffer = ByteBuffer.wrap(responseLineAndHeaderAndEmptyLine.getBytes("UTF-8"));
            SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
            socketChannel.write(byteBuffer);
            socketChannel.write(ByteBuffer.wrap(getContent()));
            socketChannel.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public byte[] getContent(){
        try {
            String requestURI = httpRequest.getRequestURI();
            if (this.status.equals("200")){
                if (requestURI.endsWith("ico")){
                    return "无此图标文件".getBytes("UTF-8");
                } else {
                    FileInputStream fileInputStream = new FileInputStream(WEB_APP_PATH + requestURI);
                    byte[] bytes = IOUtils.toByteArray(fileInputStream);
                    return bytes;
                }
            } else {
                return "你访问的资源不存在".getBytes("UTF-8");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public void write(String responseBody){
        this.version = "HTTP/1.1";
        this.status = "200";
        this.desc = "OK";
        String responseLine = this.version + " " + this.status + " " + this.desc + "\r\n";
        StringBuilder stringBuilder = new StringBuilder();
        for (Header header : headers){
            stringBuilder.append(header.getName() + ": " + header.getValue() + "\r\n");
        }
        String responseHeader = stringBuilder.toString();
        String responseEmptyLine = "\r\n";
        String responseLineAndHeaderAndEmptyLine = responseLine + responseHeader + responseEmptyLine + "\r\n";
        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
        try {
            socketChannel.write(ByteBuffer.wrap(responseLineAndHeaderAndEmptyLine.getBytes("UTF-8")));
            socketChannel.write(ByteBuffer.wrap(responseBody.getBytes("UTF-8")));
            socketChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
